package com.dede.rxbase.fragment;


import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.dede.rxbase.comm.FragmentLifecycle;
import com.dede.rxbase.util.BLog;

/**
 * 封装了布局填充和数据加载的BaseFragment
 *
 * @author hsh
 *         2018/1/18 13:55.
 */
public abstract class BaseFragment extends Fragment {

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getChildFragmentManager()
                .registerFragmentLifecycleCallbacks(FragmentLifecycle.getInstance(), false);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(getLayoutId(), container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
    }

    private boolean mIsMulti = false;// 是否已经加载过数据，避免配合切换tab的时候多次加载数据

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (getUserVisibleHint()) {
            mIsMulti = true;
            BLog.log(this, "initData");
            initData();
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser && isVisible() && !mIsMulti) {
            mIsMulti = true;
            BLog.log(this, "initData");
            initData();
        }
    }

    protected void initView() {
    }

    /**
     * 加载数据
     */
    public void initData() {
    }

    /**
     * 获取contentViewId
     *
     * @return int 布局资源id
     */
    @LayoutRes
    protected abstract int getLayoutId();

    @Override
    public void onDestroy() {
        super.onDestroy();
        getChildFragmentManager().unregisterFragmentLifecycleCallbacks(FragmentLifecycle.getInstance());
    }
}
